package com.github.m6d21.sso.support.session;

import java.util.HashMap;
import java.util.Map;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *<p>
 *
 *</p>
 *
 * @author liuyang
 * @date 2018/12/10 Mon 22:45:00
 * @since 1.0.0
 */
public class SsoSessionHolder {

    private static final Logger LOG = LoggerFactory.getLogger(SsoSessionHolder.class);

    /**
     * threadLocal保存用户Session
     */
    private static final ThreadLocal<Map<String, String>> SESSION = new ThreadLocal<>();

    private SsoSessionHolder() {
    }

    public static boolean isLogin(){
        if (MapUtils.isEmpty(getMap())) {
            return false;
        }
        return true;
    }

    public static String getAttribute(String key) {
        return getMap().get(key);
    }

    public static Map<String, String> getAllAttributes() {
        Map<String, String> localAttributes = getMap();
        if (localAttributes == null) {
            localAttributes = new HashMap<>();
        }
        return localAttributes;
    }


    public static void addAttribute(String key, String value) {
        Map<String, String> localAttributes = getMap();
        localAttributes.put(key, value);
    }

    public static void addAttributes(Map<String, String> attributes) {
        if (attributes != null) {
            Map<String, String> localAttributes = getMap();
            localAttributes.putAll(attributes);
        }
    }

    public static void clear() {
        Map<String, String> localAttributes = getMap();
        if (localAttributes != null) {
            localAttributes.clear();
        }
        SESSION.remove();
    }

    private static Map<String, String> getMap() {
        Map<String, String> attributes = SESSION.get();
        if (attributes == null) {
            attributes = new HashMap<>();
            SESSION.set(attributes);
        }
        return attributes;
    }

    public static Integer getUid() {
        return Integer.valueOf(getAttribute("uid"));
    }

    public static String getToken() {
        return getAttribute("token");
    }

    public static String getUsername() {
        return getAttribute("username");
    }

    public static String getDisplayName() {
        return getAttribute("displayName");
    }

    public static String getPhone() {
        return getAttribute("phone");
    }

}
